<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <link rel="stylesheet" href="../../lib/yzhUpload/control/css/zyUpload.css" type="text/css">
    <style>
        body {
            background-color: #ffffff;
        }

        .zyupload {
            margin: 0;
            height: auto !important;
        }

        .cancel {
            width: 20px;
            height: 20px;
            line-height: 19px;
            border: 1px solid #bcc4caf2;
            background-color: #bcc4caf2;
            border-radius: 50%;
            position: absolute; /* 父组件赋予属性relative生效 */
            right: 10px; /* 使元素处于右上角-右 */
            top: 10px; /* 使元素处于右上角-上 */
        }

        .cancel::before,
        .cancel::after {
            content: "";
            position: absolute;
            height: 14px;
            width: 2px;
            top: 3px; /* 使X处于圆中心 */
            left: 9px; /* 使X处于圆中心 */
            background-color: #353535;
        }

        .cancel::before {
            transform: rotate(45deg);
        }

        .cancel::after {
            transform: rotate(-45deg);
        }

    </style>
</head>
<body>
<div class="layui-form layuimini-form" lay-filter="role-form">
    <div class="layui-form-item">
        <label class="layui-form-label required">公告ID</label>
        <div class="layui-input-block">
            <input type="text" name="id" lay-verify="required" value="" class="layui-input" readonly>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">公告标题</label>
        <div class="layui-input-block">
            <input type="text" name="title" lay-verify="required" lay-reqtext="公告标题不能为空"
                   placeholder="请填写公告标题" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">公告类型</label>
        <div class="layui-input-block">
            <input type="radio" name="type" lay-filter="type" value="0" title="文字公告">
            <input type="radio" name="type" lay-filter="type" value="1" title="海报公告">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">弹窗周期</label>
        <div class="layui-input-block">
            <input type="text" name="ejectNumTimes" class="layui-input" id="ejectNumTimes"/>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">弹窗页面</label>
        <div class="layui-input-block">
            <input type="text" name="usedPages" placeholder="请填写弹窗页面地址" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text text-input" style="display: none">
        <label class="layui-form-label">公告内容</label>
        <div class="layui-input-block">
            <textarea name="content" class="layui-textarea" placeholder="请填写公告内容"></textarea>
        </div>
    </div>
    <div class="layui-form-item layui-form-text text-input" style="display: none">
        <label class="layui-form-label">转向地址</label>
        <div class="layui-input-block">
            <input name="jumpAddress" class="layui-input" placeholder="请填写转向地址"/>
        </div>
    </div>
    <div class="layui-form-item layui-form-text" id="image-upload" style="display: none;">
        <label class="layui-form-label">上传海报</label>
        <div class="layui-input-block">
            <div id="notice-images" style="display: flex;flex-wrap: wrap"></div>
            <div id="zyupload" class="zyupload"></div>
        </div>
        <input type="text" name="imageLink" value="" hidden>
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
            <legend>设置转向地址</legend>
        </fieldset>
        <div class="layui-form-item">
            <div class="layui-row">
                <div class="layui-col-md12">
                    <table id="data-table" lay-filter="data-table"></table>
                </div>
            </div>
            <div class="input-container">
                <table class="layui-table">
                    <colgroup>
                        <col width="300">
                        <col>
                        <col width="15%">
                    </colgroup>
                    <thead>
                    <tr>
                        <th>海报图</th>
                        <th>转向地址</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">地址来源</label>
        <div class="layui-input-block">
            <select name="addressSource">
                <option value=""></option>
                <option value="applet">小程序</option>
                <option value="outside">外部链接</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认修改</button>
        </div>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="https://unpkg.com/cos-js-sdk-v5/dist/cos-js-sdk-v5.min.js"></script>
<!-- 引用核心层插件 -->
<script type="text/javascript" src="../../lib/yzhUpload/core/zyFile.js"></script>
<!-- 引用控制层插件 -->
<script type="text/javascript" src="../../lib/yzhUpload/control/js/zyUpload.js"></script>
<script>

    let jumpAddressMap = new Map;
    // 用来缓存海报图片
    let noticeImageLinks = [];

    window.onload = function () {

        let noticeId = GetQueryString("id");
        if (isNotNull(noticeId)) {
            init(noticeId);
            // 初始化插件
            $("#zyupload").zyUpload({
                width: "650px",                 // 宽度
                height: "400px",                 // 宽度
                itemWidth: "140px",                 // 文件项的宽度
                itemHeight: "115px",                 // 文件项的高度
                url: "/meily/upload",  // 上传文件的路径
                fileType: ["jpg", "png"],// 上传文件的类型
                fileSize: 51200000,                // 上传文件的大小
                multiple: true,                    // 是否可以多个文件上传
                dragDrop: true,                    // 是否可以拖动上传文件
                tailor: true,                    // 是否可以裁剪图片
                del: true,                    // 是否可以删除文件
                finishDel: false,  				  // 是否在上传文件完成后删除预览
                /* 外部获得的回调接口 */
                onSelect: function (files, allFiles) {                    // 选择文件的回调方法
                    console.info("当前选择了以下文件：");
                    console.info(files);
                    console.info("之前没上传的文件：");
                    console.info(allFiles);
                },
                onDelete: function (file, surplusFiles) {                     // 删除一个文件的回调方法
                    console.info("当前删除了此文件：");
                    console.info(file);
                    console.info("当前剩余的文件：");
                    console.info(surplusFiles);
                },
                onSuccess: function (file, response) {                    // 文件上传成功的回调方法
                    console.info("此文件上传成功：");
                    if (isNotNull(response.url)) {
                        uploadAddToImg(response.url);
                    }
                },
                onFailure: function (file) {                    // 文件上传失败的回调方法
                    console.info("此文件上传失败：");
                    console.info(file);
                },
                onComplete: function (responseInfo) {           // 上传完成的回调方法
                    console.info("文件上传完成");
                    console.info(responseInfo);
                }
            });
        } else {
            const iframeIndex = parent.layer.getFrameIndex(window.name);
            parent.layer.close(iframeIndex);
        }
    }

    /**
     * 初始化数据
     */
    function init(id) {
        $.ajax({
            type: "get",
            url: '/notice/' + id,
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function (req) {
                if (req.code === '200') {
                    layui.use(['form', 'numberInput'], function () {
                        let form = layui.form,
                            numberInput = layui.numberInput;

                        const noticeData = req?.data;
                        if (noticeData?.type === '1') {
                            // 初始化，隐藏文本输入框，显示图片上传
                            $('.text-input').hide();
                            $('#image-upload').show();
                        } else {
                            // 初始化，显示文本输入框，隐藏图片上传
                            $('.text-input').show();
                            $('#image-upload').hide();

                        }

                        let content = '';
                        let jumpAddress = '';
                        let contentList = JSON.parse(noticeData.content)
                        if (contentList == null || contentList === void 0 || contentList.length === 0) {
                            return "";
                        }
                        if (noticeData.type == 0) {
                            content = contentList[0]?.contentText;
                            jumpAddress = contentList[0]?.jumpAddress;
                        } else {
                            contentList.forEach(function (content) {
                                jumpAddressMap.set(content['noticeImage'], content['jumpAddress'])
                                uploadAddToImg(content['noticeImage'])
                            });
                        }
                        form.val('role-form', {
                            "id": noticeData?.id,
                            "title": noticeData?.title,
                            'type': noticeData?.type,
                            "content": content,
                            "addressSource": noticeData?.addressSource,
                            "usedPages": noticeData?.usedPages,
                            "jumpAddress": jumpAddress,
                        });

                        let defEjectNumTimes = 1;
                        if (noticeData?.ejectNumTimes) {
                            defEjectNumTimes = noticeData.ejectNumTimes;
                        }

                        numberInput.render("#ejectNumTimes", {
                            max: 9,
                            min: 1,
                            defaultValue: defEjectNumTimes,
                            step: 1,
                        });

                    })
                } else {
                    layer.msg("数据异常，请重试");
                    // 关闭弹出层
                    setTimeout(function () {
                        let iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(iframeIndex);
                    }, 1500);
                }

            },
            error: function (e) {
                layer.msg("数据有误");
            }
        })
    }

    layui.use(['form'], function () {
        const form = layui.form,
            layer = layui.layer,
            $ = layui.$;


        // 监听公告类型单选框
        form.on('radio(type)', function (data) {
            var type = data.value;
            if (type === '0') {
                $('.text-input').show();
                $('#image-upload').hide();
            } else if (type === '1') {
                $('.text-input').hide();
                $('#image-upload').show();
            }
        });

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            const formData = data?.field;
            let isAddressSourceMust = false;
            let contentList = [];
            if (formData.type === '1') {
                let imageLikeList = formData.imageLink.split(",")
                imageLikeList.forEach(function (image) {
                    if (isNotNull(formData[image])) {
                        isAddressSourceMust = true;
                    }
                    const content = {
                        noticeImage: image,
                        jumpAddress: formData[image]
                    }
                    contentList.push(content)
                })
            } else {
                const content = {
                    contentText: formData.content,
                    jumpAddress: formData.jumpAddress
                }
                if (isNotNull(formData.jumpAddress)) {
                    isAddressSourceMust = true;
                }
                contentList.push(content)
            }
            if (isAddressSourceMust) {
                // 如果转向地址被填写，地址来源必须被填写
                if (!isNotNull(formData.addressSource)) {
                    layer.msg("请选择地址来源");
                    return false;
                }
            }
            // 组装数据
            const noticeData = {
                id: formData?.id,
                title: formData?.title,
                status: formData?.status,
                content: JSON.stringify(contentList),
                type: formData?.type,
                ejectNumTimes: formData?.ejectNumTimes,
                addressSource: formData?.addressSource,
                usedPages: formData?.usedPages
            }
            var index = layer.alert("确定提交修改吗？", {
                title: '提示'
            }, function () {
                let myMsg = layer.msg("正在提交...", {
                    icon: 16,
                    time: -1
                })
                $.ajax({
                    type: "post",
                    url: '/notice/edit',
                    data: JSON.stringify(noticeData),
                    dataType: 'json',
                    contentType: 'application/json; charset=UTF-8',
                    success: function (req) {
                        if (req.code === '200') {
                            layer.msg("修改成功");
                            layer.close(index);
                            // 关闭弹出层
                            setTimeout(function () {
                                layer.close(myMsg);//手动关闭
                                let iframeIndex = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(iframeIndex);
                            }, 1500);
                        }

                    },
                    error: function (e) {
                        layer.msg("修改失败");
                        layer.close(myMsg);//手动关闭
                    }
                })

            });
            return false;
        });

    });

    /**
     * 上传文件完成后将文件地址添加到图片列表中
     * @param url
     */
    function uploadAddToImg(url) {
        let imageLinkVal = $('input[name="imageLink"]').val();
        if (isNotNull(url)) {
            if (isNotNull(imageLinkVal)) {
                imageLinkVal += "," + url;
            } else {
                imageLinkVal = url;
            }
            $('input[name="imageLink"]').val(imageLinkVal);
            renderImages(imageLinkVal);
        }
    }

    /**
     * 渲染加载的图片
     */
    function renderImages(imageLinks) {
        if (!isNotNull(imageLinks)) {
            renderTable([]);
            return
        }
        let imgs_arr = imageLinks.split(",");
        renderTable(imgs_arr);
    }

    function renderTable(imageLinks) {
        var tableHtml = '<table class="layui-table">'
            + '<colgroup>'
            + '<col width="300">'
            + '<col>'
            + '<col width="15%">'
            + '</colgroup>'
            + '<thead>'
            + '<tr>'
            + '<th>海报图片</th>'
            + '<th>转向地址</th>'
            + '<th>操作</th>'
            + '</tr>'
            + '</thead>'
            + '<tbody>';
        let i = 0;
        imageLinks.forEach(function (image) {
            let jumpAddress = jumpAddressMap?.get(image) ?? '';
            tableHtml += '<tr>'
                + '<td class="laytable-cell-customization"><img src="' + image + '" style="width: 100%;height: 80px;"/></td>'
                + '<td><input type="text" name="' + image + '" value="' + jumpAddress + '" class="layui-input"></td>'
                + '<td>'
                + '<button type="button" class="layui-btn layui-btn-danger layui-btn-sm" onclick="delImage(' + i + ')">删除</button>'
                + '<button type="button" class="layui-btn layui-btn layui-btn-sm" onclick="moveUpImage(' + i + ')">上移</button>'
                + '<button type="button" class="layui-btn layui-btn layui-btn-sm" onclick="moveDownImage(' + i + ')">下移</button>'
                + ' </td>'
                + '</tr>';
            i++;
        });
        tableHtml += '</tbody>'
            + '</table>';
        $('.input-container').empty().append(tableHtml);
        noticeImageLinks = imageLinks;
        // 重新渲染表单
        layui.form.render();
    }

    /**
     * 删除图片
     */
    function delImage(index) {
        let image_val = $('input[name="imageLink"]').val();
        let new_image_val = '';
        if (isNotNull(image_val)) {
            let imgs_arr = image_val.split(",");
            if (imgs_arr.length > 0) {
                for (const i in imgs_arr) {
                    if (i == index) {
                        continue;
                    }
                    if (isNotNull(new_image_val)) {
                        new_image_val += "," + imgs_arr[i];
                    } else {
                        new_image_val = imgs_arr[i];
                    }
                }
            }
        }
        $('input[name="imageLink"]').val(new_image_val);
        renderImages(new_image_val);
    }

    /**
     * 图片上传完成后清空文件夹
     */
    function clear() {
        $.ajax({
            type: "post",
            url: '/meily/file/clear',
            dataType: 'json',
            contentType: 'application/json; charset=UTF-8',
            success: function (req) {
                console.log(req);
            },
            error: function (e) {
                console.log(e);
            }
        })
    }

    /**
     * 移动海报图片排序
     */
    function moveUpImage(index) {
        if (index > 0) {
            let temp = noticeImageLinks[index];
            noticeImageLinks[index] = noticeImageLinks[index - 1];
            noticeImageLinks[index - 1] = temp;
            renderTable(noticeImageLinks);
            changeImageLinkVal();
        }
    }

    function moveDownImage(index) {
        if (index < noticeImageLinks.length - 1) {
            let temp = noticeImageLinks[index];
            noticeImageLinks[index] = noticeImageLinks[index + 1];
            noticeImageLinks[index + 1] = temp;
            renderTable(noticeImageLinks);
            changeImageLinkVal();
        }
    }

    /**
     * 更改表单图片表单的值
     */
    function changeImageLinkVal() {
        let imageLinkVal = "";
        noticeImageLinks.forEach(function (image) {
            if (isNotNull(imageLinkVal)) {
                imageLinkVal += "," + image;
            } else {
                imageLinkVal = image;
            }
        })
        $('input[name="imageLink"]').val(imageLinkVal);
    }

</script>
</body>
</html>
